package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.entity.WeChatEntity;
import com.example.http.HttpClinetUtil;
import com.example.util.JsonUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
public class WeChatController {
    private static final String GET_TOKEN_1 = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx44f85f4da5d17823&secret=bf2b4faae8adccfda5fb05a22b97ed4f&code=";
    private static final String GET_TOKEN_3 = "&grant_type=authorization_code";
    private static final String GET_USER_1 = "https://api.weixin.qq.com/sns/userinfo?access_token=";
    private static final String GET_USER_3 = "&openid=";
    private static final String GET_USER_5 = "&lang=zh_CN";

    @RequestMapping("/wechat")
    public void redict(HttpServletResponse response)
    {
        try {
            //response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx44f85f4da5d17823&redirect_uri=https://localhost:80/getCode&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect");
            response.sendRedirect("https://www.baidu.com");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("重定向失败");
            //throw new Exception();
        }
    }

    @RequestMapping("/getCode")
    public String getCode(String code)//state参数，可以防止别人攻击
    {
        //code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
        System.out.println(code);
        if (null==code)
        {
            System.out.println("code为null，请重新授权");
            return null;
        }
        //获取code之后发送httpget请求，获取token，获取的是string，取药转化成json对象，取得token,考虑code无效情况
        String tokenUrl = GET_TOKEN_1 + code + GET_TOKEN_3;
        //TestString tokenUrl = "http://localhost:80/getToken";//本地测试
        String tokenResponse = HttpClinetUtil.doGet(tokenUrl);
        if (null == tokenResponse)
            return null;//没有获得返回token请求，可以抛异常
        String token = (String) JsonUtil.getByName("access_token",tokenResponse);
        String openId = (String) JsonUtil.getByName("openid",tokenResponse);
        System.out.println(openId);
        //如果token为null，说明code过期或者错误，需要重新用户退出，重新关注然后授权
        if (null==token||null==openId)
            return null;
        //此处考虑需不需要刷新，登录是不需要的，只是token两个小时会过期，可能每次操作都需要获取token以及openid

        //根据token和openid，openid以后都有了，获取用户信息，所以只有需要用户信息时才需要token
        String userUrl = GET_USER_1 + token + GET_USER_3 + openId + GET_USER_5;
        //TestString userUrl = "http://localhost:80/getMyUserInfo";
        String userInfo = HttpClinetUtil.doGet(userUrl);
        WeChatEntity entity = JSONObject.parseObject(userInfo,WeChatEntity.class);
        System.out.println(entity.toString());
        //根据数据库里面的user是否youopenid，没有则入库，并且算是注册，有就是登录，是否需要更新用户微信信息？
        return code;
    }

    //模拟一个token数据和一个用户的数据
    @RequestMapping("/getToken")
    public String getToken()
    {
        return "{\"access_token\":\"8_tHKMu2gntf5WumF0egJQUZ1fpRWOcOr-nqhmw8KOwh_HwMG56rn04yOkb" +
                "znFIX5AK0_ZDkzQ_fL8feyJWHTNpplh7fz6-1OXP4M_gyurIWM\",\n" +
                " \"expires_in\":7200,\n" +
                " \"refresh_token\":\"8_xORCTuBW9O3xgvoRfx0FmLYApETOdIXBoirJLsg9BN6QxtNo" +
                "kVpMnKeg8fFoNNu9xsFbhe9BAuBq1MTiyN84VRgWpe6KKdE127v6xvhN5-0\",\n" +
                " \"openid\":\"oEixV0m2cva-ZlPf48Fimeo9Mp58\",\n" +
                " \"scope\":\"snsapi_userinfo\"}";
    }

    @RequestMapping("/getMyUserInfo")
    public String getMyUserInfo()
    {
        return "{\"openid\":\"oEixV0m2cva-ZlPf48Fimeo9Mp58\",\"nickname\":\"朱长华\",\"sex\":1,\"language\":\"zh_CN\",\"city\":\"南京\"," +
                "\"province\":\"江苏\",\"country\":\"中国\",\n" +
                " \"headimgurl\":\"http:\\/\\/thirdwx.qlogo.cn\\/mmopen\\/vi_32\\/DYAIOgq83eom6Erof6WLblltiaNn" +
                "w8ne4VpichplQJuguRaYQwa3KmhNloHVe63WZocwOiamSQEdKaiaF340lccyiaQ\\/132\",\"privilege\":[]}";
    }


}
